package ar.com.sectorwine.jms;

import javax.annotation.PostConstruct;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class JmsMessageProducer {

	private static final Logger logger = LoggerFactory
			.getLogger(JmsMessageProducer.class);

	protected static final String MESSAGE_COUNT = "messageCount";
	protected static final String MESSAGE_FROM = "from";
	protected static final String MESSAGE_TO = "to";

	@Autowired
	private JmsTemplate template = null;
	private int messageCount = 10;

//	/**
//	 * Generates JMS messages
//	 */
//	@PostConstruct
//	public void generateMessages() throws JMSException {
//		for (int i = 0; i < messageCount; i++) {
//			final int index = i;
//			final String text = "Message number is " + i + ".";
//
//			template.send(new MessageCreator() {
//				public Message createMessage(Session session)
//						throws JMSException {
//					TextMessage message = session.createTextMessage(text);
//					message.setIntProperty(MESSAGE_COUNT, index);
//					message.setStringProperty(MESSAGE_FROM, "carlos");
//					message.setStringProperty(MESSAGE_TO, "ismael");
//
//					logger.info("-----> Sending: /n message: " + text + "to: "+"ismael" + "from: "+"carlos");
//
//					return message;
//				}
//			});
//		}
//	}

	public void sendMessage(final String message, final String from, final String to) {//throws JMSException {

		template.send(new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				
				TextMessage textMessage = session.createTextMessage(message);
				
				textMessage.setIntProperty(MESSAGE_COUNT, 0);
				textMessage.setStringProperty(MESSAGE_FROM, from);
				textMessage.setStringProperty(MESSAGE_TO, to);
				
				logger.info("##########>> Sending: /n message: " + message + "to: "+to+ "from: "+from);
				return textMessage;
			}
		});

	}

}
